package com.fourth.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.fourth.dto.OrdersDto;
import com.fourth.entity.*;
import com.fourth.service.AddressService;
import com.fourth.service.CartService;
import com.fourth.service.GoodsService;
import com.fourth.service.OrdersService;
import com.fourth.service.impl.RabbitSenderService;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping
public class OrdersController {


    @Resource
    private OrdersService ordersService;
    @Resource
    private GoodsService goodsService;
    @Resource
    private CartService cartService;
    @Resource
    private AddressService addressService;

    @Resource
    private RabbitSenderService rabbitSenderService;


    @RequestMapping(value = "/showOrder",method= RequestMethod.GET)
    public String skip(){

        return "WEB-INF/showOrder";
    }

    /**
     * 查询订单的详情进行规划：未支付订单、已支付订单，、已取消订单
     * @param oStatus
     * @param session
     * @return
     */
    @GetMapping("/selectOStatusOrders")
    @ResponseBody
    public List<OrdersDto> selectOStatusOrders(Integer oStatus, HttpSession session ){
        System.out.println(oStatus);

        //获取登录的用户ID
        Integer uId = (Integer) session.getAttribute("uId");
        System.out.println("用户登录的ID："+uId);

        System.out.println("oStatus"+oStatus);
        //调用service层返回数据
        List<OrdersDto> ordersDtoList = ordersService.selectOStatusOrders(uId, oStatus);
        return ordersDtoList;

    }

    /**
     * 取消订单，把订单状态修改为2（与取消订单）
     * @param oNo
     * @param attr
     * @return
     */
    @RequestMapping("/cancelOrder")
    @ResponseBody
    public String cancelOrder(String oNo, RedirectAttributes attr){

        Boolean updateOStatusOrders = ordersService.updateOStatusOrders(oNo);
        System.out.println(updateOStatusOrders);
        if (updateOStatusOrders){

            //attr.addFlashAttribute("oStatus",0);

            //return "redirect:selectOStatusOrders?oStatus=0";
            return "true";
        }else {
            return "false";
        }
    }

    /**
     * 获取改订单的总价格
     * @param oNo
     * @return
     */
    @RequestMapping("/continuePaySelectPrice")
    @ResponseBody
    public List<Orders> continuePaySelectPrice(String oNo) {
        System.out.println("查询价格的订单编号：" + oNo);
        List<Orders> orders = ordersService.selectOrdersByONo(oNo);
        System.out.println(orders);
        return orders;
    }
    @GetMapping("/settlement")
    @ResponseBody
    @Transactional
    public String settlement(HttpServletRequest request, HttpSession session){

        //获取当前登录的用户ID
        Integer uId = (Integer) session.getAttribute("uId");

        //接收 前端的购物车结算商品数据
        String arr = request.getParameter("arr");
        List<Cart> parse = (ArrayList) JSONUtils.parse(arr);

        //一个临时存储数据的CartItem集合:
        List<CartItem> scratchCarts = new ArrayList<>();
        for (int i = 0; i < parse.size(); i++) {
            CartItem cart = JSON.parseObject(JSON.toJSONString(parse.get(i)), CartItem.class);
            CartItem scratchCart = new CartItem();
            scratchCart.setGoodsId(String.valueOf(cart.getGoodsId()));
            scratchCart.setNum(cart.getNum());
            scratchCarts.add(scratchCart);
        }

        // session.setAttribute("uId",1);//todo 可删除注释

        //1.生成订单
        //订单默认状态为0（未支付）
        List<Orders> ordersList = new ArrayList<>();
        System.out.println("scratchCarts"+scratchCarts.size());

        //订单编号生成（唯一）
        DateFormat fm = new SimpleDateFormat("yyyyMMddhhmmssSSS");
        String cTime = fm.format(new Date());
        String uuid = UUID.randomUUID().toString().substring(0, 6);
        String newOno = cTime+uuid;
        for (CartItem scratchCart : scratchCarts) {
            Orders orders = new Orders();
            orders.setONo(newOno);

            //订单状态：默认为0 （请区别订单状态和商品状态）
            orders.setOStatus(0);
            orders.setONum(scratchCart.getNum());
            orders.setOAppraiseStatus(0);
            orders.setOCreateTime(new Date());

            orders.setOUserId(uId);

            //2.商品相关属性set
            Goods goods = goodsService.selectGoodsById(Integer.valueOf(scratchCart.getGoodsId()));
            orders.setOGoodPrice(goods.getPrice());
            orders.setOGoodTitle(goods.getTitle());
            orders.setOGoodImg(goods.getSmallPic());
            orders.setOGoodId(scratchCart.getGoodsId());

            //插入订单集合
            ordersList.add(orders);
            //插入订单数据库
            int i = ordersService.insertOrder(orders);
        }
        System.out.println("生成订单打印：");//todo 可删除注释
        for (Orders orders : ordersList) {
            System.out.println("订单生成成功：订单编号："+orders);
        }



        //2.删除 session/sql 购物车内容
        List<Cart> myCart = (List<Cart>) session.getAttribute("myCart");
        if (null!=myCart){
            session.removeAttribute("myCart");
        }
        List<Cart> myCart2 = (List<Cart>) session.getAttribute("myCart2");
        if (null!=myCart2){
            session.removeAttribute("myCart");
        }
        //执行删除sql记录（根据用户id删除与用户相关的所有购物车条目）
        int i = ordersService.delAllCartByUid(uId);



        //3.获取用户 的收货地址并插入到 订单地址表
        Address address = addressService.selectTDAddressByUid(uId);
        List<Orders> orders = ordersService.selectOrdersByUid(uId);

        System.out.println("address:"+address);
        System.out.println("orders:"+orders);

        //防空判断
        if (address!=null&&orders!=null&&orders.size()!=0){
            for (Orders order : orders) {
                ordersService.insertOrderAndAddress(address.getAId(),order.getONo());
            }
        }else {
            System.out.println("地址或订单为空，添加失败");
        }

//         rabbitSenderService.sendKillSuccessOrderExpireMsg(newOno);
        return newOno;


    }




}
